<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { loginApi } from '@/apis/common/loginApi'

const bindTypeParams = ref<Record<string, Record<string, string>>>({})
const selectedType = ref()
const dialogVisible = ref(false)

async function loadBindSetting() {
  const redirectUri = `${location.origin}/#/codeCallback?type=bind`
  const { loginTypeParams } = await loginApi.queryLoginSettings(redirectUri)
  bindTypeParams.value = loginTypeParams
}

function onSelect(type: string) {
  if (bindTypeParams.value[type].authorizeUrl) {
    window.open(bindTypeParams.value[type].authorizeUrl)
  }
  else {
    selectedType.value = type
    dialogVisible.value = true
  }
}

onMounted(loadBindSetting)

async function scanCallback(code: string, type: string) {
  await loginApi.bindAccount({ thirdCode: code, loginType: type })
  ElMessage.success('绑定成功')
  dialogVisible.value = false
}

const bindTypes = ref([
  { name: 'GITEE', src: 'https://gitee.com/favicon.ico' },
  { name: 'DINGTALK', src: 'https://img.alicdn.com/imgextra/i4/O1CN01RtfAks1Xa6qJFAekm_!!6000000002939-2-tps-128-128.png' },
  { name: 'WECOM', src: 'https://res.wx.qq.com/a/wx_fed/assets/res/NTI4MWU5.ico' },
  { name: 'WECHAT', src: 'https://gitee.com/favicon.ico' },
])
</script>

<template>
  <div class="my-2 text-sm font-bold">
    绑定其他账号
  </div>
  <div class="flex flex-row items-center gap-2">
    <template v-for="type in bindTypes" :key="type.name">
      <img v-if="bindTypeParams[type.name]" :src="type.src" class="h-8 w-8 cursor-pointer" @click="onSelect(type.name)">
    </template>
  </div>
  <el-dialog
    v-model="dialogVisible"
    destroy-on-close
    width="400px"
  >
    <DingtalkCode v-if="selectedType === 'DINGTALK'" :params="bindTypeParams.DINGTALK" @callback="(code) => scanCallback(code, 'DINGTALK')" />
  </el-dialog>
</template>
